package com.webserver.controller;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.webserver.vo.Write;

import java.io.*;

public class ArticleController {
    public static final String WRITE_DIR = "./write/";
    static {
        File dirs = new File(WRITE_DIR);
        if (!dirs.exists()) {//如果该目录不存在则自动创建
            dirs.mkdirs();
        }
    }
    public void write(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理提交...");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        if (title == null || author == null) {
            File file = new File("./webapps/myweb/write_fail.html");
            response.setEntity(file);
            return;
        }
        if (content == null) {
            File file = new File("./webapps/myweb/write_err.html");
            response.setEntity(file);
            return;
        }
        Write write = new Write(title, author, content);
        try (FileOutputStream fos = new FileOutputStream(WRITE_DIR + author + ".obj");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(write);
            File file = new File("./webapps/myweb/write_success.html");
            response.setEntity(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("文章提交成功!");
    }
    public void watch(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理查看...");
        String autohr = request.getParameter("author");
        if (autohr==null){
            File file =new File("./webapps/myweb/watch_fail");
            response.setEntity(file);
            return;
        }
        File write = new File(WRITE_DIR+autohr+".obj");
        if (write.exists()){
            try(FileInputStream fis = new FileInputStream(write);
                ObjectInputStream ois = new ObjectInputStream(fis)) {
                Write writeuser = (Write)ois.readObject();
                System.out.println(writeuser);
                File file = new File("./webapps/myweb/watch_success.html");
                response.setEntity(file);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        System.out.println("查看成功!");
    }
}
